# @Time : 2021/10/25 19:50
# @Author : Li Kunlun
# @Description : 线程安全问题-问题复现
import threading
import time


class Account:
    def __init__(self, balance):
        self.balanece = balance


def draw(account, amount):
    if account.balanece >= amount:
        # 导致当前线程阻塞，进行线程之间的切换
        time.sleep(0.1)  # 加上这行语句时，一定会出现线程安全问题
        print(threading.current_thread().name, "取钱成功")
        account.balanece -= amount
        print(threading.current_thread().name, "余额", account.balanece)
    else:
        print(threading.current_thread().name, "取钱失败，余额不足")


if __name__ == '__main__':
    account = Account(1000)
    ta = threading.Thread(name="ta", target=draw, args=(account, 800))
    tb = threading.Thread(name="tb", target=draw, args=(account, 800))

    ta.start()
    tb.start()
    """
    程序执行结果（存在打印的问题）：
        ta 取钱成功
        tatb 取钱成功
        tb 余额 -600
         余额 200
    """
